package com.scu.phototabuser.ui.login.login;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.test.espresso.core.deps.guava.base.Strings;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.scu.phototabuser.Consts;
import com.scu.phototabuser.R;
import com.scu.phototabuser.ui.login.FindPasswordActivity;
import com.scu.phototabuser.ui.taskgroup.UserChosenDecisionMaker;
import com.scu.phototabuser.util.FragmentUtil;
import com.scu.phototabuser.util.MD5;
import com.scu.phototabuser.util.NetworkUtil;
import com.scu.phototabuser.util.ToastUtil;
import com.scu.phototabuser.widgets.EditTextWithImgLeft;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.scu.phototabuser.util.Predictions.checkNotNull;
/**
 * Created by tianfei on 2017/4/8.
 */

public class LoginFragment extends Fragment implements LoginContract.LoginView {

    private LoginContract.Presenter mPresenter;

    private static final String TAG = "LoginFragment";
    private static final int REQUEST_SIGNUP = 0;

    private String _email;
    private String _MD5pass;

    @BindView(R.id.input_email) EditTextWithImgLeft _emailText;
    @BindView(R.id.input_password) EditTextWithImgLeft _passwordText;
    @BindView(R.id.btn_login) AppCompatButton _loginButton;

    @OnClick(R.id.btn_login)
    public void login(){

        if (!NetworkUtil.isNetworkAviliable(getActivity())){
            ToastUtil.makeToast(getActivity(),Consts.NO_NETWORK);
            return;
        }

        //获取输入的内容并校验
        _email = _emailText.getText();
        String password = _passwordText.getText();

        //输入不合法
        if (!validate(_email,password)){
            return;
        }

        _MD5pass= MD5.getMD5(password.getBytes());

        _loginButton.setEnabled(false);
        final ProgressDialog progressDialog = new ProgressDialog(getActivity(),
                R.style.TransparentProgressDialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Login...");
        progressDialog.show();

        //调用presenter进行login
        mPresenter.doLogin(_email, _MD5pass, new LoginContract.LoginCallback() {
            @Override
            public void showSuccess() {
                progressDialog.cancel();
            }

            @Override
            public void showFailed(Integer code,String msg) {
                progressDialog.cancel();
                Log.e(TAG, "showFailed: "+code);
                ToastUtil.makeAppContextToast(msg);
                _loginButton.setEnabled(true);
            }
        });
    }

    @OnClick(R.id.link_signup)
    public void change2signUp(){

        if (!NetworkUtil.isNetworkAviliable(getActivity())){
            ToastUtil.makeToast(getActivity(), Consts.NO_NETWORK);
            return;
        }

        SingUpFragment singUp =SingUpFragment.newInstance(new LoginContract.showEmailCallback(){
            @Override
            public void showEmail(String email) {
                showEmailFromSignUp(email);
            }
        });
        //bind presenter
        SingUpPresenter singUpPresenter=new SingUpPresenter(singUp);
        FragmentUtil.addFragmentToActivity(getFragmentManager(),R.id.container,singUp,null,true);
    }

    @OnClick(R.id.forget_password)
    public void jump2FindPassword(){
        Intent i2Find = new Intent(getActivity(), FindPasswordActivity.class);
        startActivity(i2Find);
    }

    @OnClick(R.id.login_wechat)
    public void login_with_wechat(){
        ToastUtil.makeToast(getActivity(),"微信开发者接口升级，暂停使用微信登录");
    }
    public boolean validate(String email,String password) {
        boolean valid = true;

        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            _emailText.setError(Consts.EMAIL_ADDR_ERR);
            valid = false;
        } else {
            _emailText.setError(null);
            _email=_emailText.getText();
        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 14) {
            _passwordText.setError(Consts.PASSWORD_FORMAT_ERR);
            valid = false;
        } else {
            _passwordText.setError(null);
        }

        return valid;
    }

    public LoginFragment(){}

    public static LoginFragment newInstance(){
        return new LoginFragment();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root=inflater.inflate(R.layout.fragment_login,container,false);
        ButterKnife.bind(this,root);
        return root;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (!Strings.isNullOrEmpty(_email)){
            Log.e(TAG, "onResume: "+_email);
            _emailText.setText(_email);
        }
        if (_passwordText!=null){
           _passwordText.setText(null);
        }
    }

    @Override
    public void showEmailFromSignUp(String email) {
        Log.e(TAG, "showEmailFromSignUp: "+email+_email);
        _email=email;
    }

    @Override
    public void setPresenter(LoginContract.Presenter presenter) {
        this.mPresenter=checkNotNull(presenter);
    }

    @Override
    public void setProgressBarVisibility(boolean visibility) {

    }

    @Override
    public void jumpToHome() {

        Intent intent=new Intent(getActivity(), UserChosenDecisionMaker.class);
        intent.putExtra("fromlogin",true);
        startActivity(intent);

        //释放presenter
        mPresenter.release();
        getActivity().finish();
    }
}

